import { IRootReducerState } from '@/store/root-reducer';
import { createContext, useContext, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useSelector, shallowEqual } from 'react-redux';
import * as authAction from '@/redux/auth/auth-actions';
import { PreferenceKey } from '@/redux/auth/auth-slice';

export enum NavStatus {
  hide,
  show,
  lock,
}

const MainContext = createContext<any>(null);
export function useMainContext() {
  return useContext(MainContext);
}
export const MainConsumer = MainContext.Consumer;

const MainProvider = ({ MainEvents, children }: any) => {
  const dispatch = useDispatch<any>();
  const {
    auth: { preference },
  } = useSelector<IRootReducerState, any>(
    (state) => ({ auth: state.auth }),
    shallowEqual
  );

  const [loading, setLoading] = useState(false);
  const [locking, setLocking] = useState(
    preference[PreferenceKey.MAINSIDERLOCKKEY] ?? NavStatus.lock
  );

  useEffect(() => {
    dispatch(
      authAction.updatePreference(PreferenceKey.MAINSIDERLOCKKEY, locking)
    );
  }, [locking]);

  const value = {
    loading,
    setLoading,
    locking,
    setLocking,
  };
  return <MainContext.Provider value={value}>{children}</MainContext.Provider>;
};

export default MainProvider;
